package com.luoqiu.springCloud.conreoller;

import com.luoqiu.entities.Payment;
import com.luoqiu.entities.Result;
import com.luoqiu.springCloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author 洛秋y
 * @date 2020/11/10 17:20
 */
@RestController
@Slf4j
public class OrderController {

    //private static final String url = "http://localhost:8001";
    //在服务提供方是多服务的情况下 此时调用服务采用服务名调用
    private static final String url = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private LoadBalancer loadBalancer;
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/con/create")
    public Result create(@RequestBody Payment payment) {
        return restTemplate.postForObject(url + "/add", payment, Result.class);
    }

    @GetMapping(value = "/con/get/{id}")
    public Result<Payment> get (@PathVariable("id")Long id) {
        return restTemplate.getForObject(url + "/get", Result.class);
    }

    @GetMapping(value = "/con/myself")
    public String getLoadBalancer() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() == 0) {
            return null;
        }
        ServiceInstance instance = loadBalancer.instance(instances);
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri + "/con/get", String.class);
    }
}
